package com.wenhai.leetcode.tree;

/**
 * @ClassName _307区域和检索数组可修改
 * @Description https://leetcode-cn.com/problems/range-sum-query-mutable/
 * @Author 谢文海
 * @Date 2021/3/22 0:10
 * @Version 1.0
 **/
public class _307区域和检索数组可修改 {

    private final int[] sum;
    private final int[] data;
    public _307区域和检索数组可修改(int[] nums) {
        this.data = new int[nums.length];
        for (int i = 0; i < nums.length; i++) {
            this.data[i] = nums[i];
        }
        this.sum = new int[nums.length + 1];
        this.sum[0] = 0;
        for (int i = 1; i < sum.length; i++) {
            sum[i] = sum[i - 1] + nums[i - 1];
        }

    }

    public void update(int index, int val) {
        data[index] = val;
        for (int i = index + 1; i < sum.length; i++) {
            sum[i] = sum[i - 1] + data[i - 1];
        }
    }

    public int sumRange(int left, int right) {
        return sum[right + 1] - sum[left];
    }
}
